#include "element.h"

Element::Element()
{
    radius = DEFAULT_RADIUS;
    moveCircle = new QGraphicsEllipseItem(this);
    nodes = new QVector<QGraphicsEllipseItem*>();
    nodeCounter = 1;
}

Element::~Element()
{
    delete moveCircle;
    delete nodes;
}

QGraphicsEllipseItem* Element::getMoveCircle()
{
    return moveCircle;
}

void Element::setMoveCircleRadius(int radius)
{
    moveCircle->setRect(0, 0, radius, radius);
    moveCircle->setPos(-radius/2, -radius/2);
}

QRectF Element::boundingRect() const
{
    return QRect(-radius, -radius, 2*radius, 2*radius);
}

QVariant Element::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemSelectedHasChanged)
    {
        emit selectedChange(this);
    }
    return value;
}

void Element::setPainter(QPainter *painter)
{
    QPen pen;
    if (isSelected())
    {
        pen.setStyle(Qt::DashLine);
    }
    else
    {
        pen.setStyle(Qt::SolidLine);
    }
    painter->setPen(pen);
}

void Element::addNode(qreal x, qreal y)
{
    QGraphicsEllipseItem *node = new QGraphicsEllipseItem(this);
    node->setFlag(QGraphicsItem::ItemIsMovable, true);
    node->setFlag(QGraphicsItem::ItemIsSelectable, true);
    node->setRect(0, 0, 2*NODE_RADIUS, 2*NODE_RADIUS);
    node->setPos(x - pos().x() - NODE_RADIUS, y - pos().y() - NODE_RADIUS);
    nodes->append(node);

    QGraphicsTextItem *label = new QGraphicsTextItem(QString::number(nodeCounter++), node);
    label->setPos(0, -2);
}

QVector<QGraphicsEllipseItem*> Element::getNodes()
{
    return *nodes;
}

void Element::removeNode(QGraphicsEllipseItem *item)
{
    for (int i = 0; i < nodes->size(); i++)
    {
        if (nodes->at(i) == item)
        {
            nodes->remove(i);
            return;
        }
    }
}
